package com.fsgom.gool.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fsgom.common.layout.FrontLayout;
import com.fsgom.common.layout.LayoutName;
import com.fsgom.common.layout.element.GlobalLayoutElement;
import com.fsgom.common.web.layout.annotations.Layout;
import com.fsgom.common.web.layout.annotations.LayoutConfigure;
import com.fsgom.gool.bean.GoolArtclInfo;
import com.fsgom.gool.bean.GoolUserInfo;
import com.fsgom.gool.service.GoolArtclService;
import com.fsgom.gool.service.GoolMainService;
import com.fsgom.gool.service.GoolUserService;

@Controller
@RequestMapping("/gool")
public class GoolMainController {
	
	private final Logger log = Logger.getLogger(GoolMainController.class);
	private final static String VIEWSPACE = "/gool";
	private final static String NOTFOUND = "/common/notfound";
	
	@Autowired
	private GoolMainService mainSrv;
	@Autowired
	private GoolArtclService artclSrv;
	@Autowired
	private GoolUserService userSrv;

	@LayoutConfigure
	public void setupLayout(FrontLayout layoutConfig, Map<String, Object> params) {
		//layoutConfig.getElement(GlobalLayoutElement.class).addCssPrefix(null);
		//layoutConfig.getElement(GlobalLayoutElement.class).addJsPrefix(null);
		layoutConfig.getElement(GlobalLayoutElement.class).setTitlePrefix("굴곰");
		layoutConfig.getElement(GlobalLayoutElement.class).setTitlePostfix("사육곰");
	}
	
	@Layout(value = LayoutName.DEFAULT)
	@RequestMapping("/*")
	public String mainPage(HttpServletRequest request, ModelMap modelMap, @RequestParam(value="passWd", defaultValue="") String passWd  ) {
		String addr = request.getRequestURI();
		String userId = getUserIdFromUri(addr);
		if (userId == null) {
			return NOTFOUND;
		}
		GoolUserInfo userInfo = userSrv.getUserInfo(null, userId);
		if (userInfo == null) {
			return NOTFOUND;
		}
		boolean isOwner = userSrv.isOwner(userInfo, userId, passWd);
		modelMap.put("isOwner", isOwner);
		
		GoolArtclInfo artclInfo = artclSrv.getArtclInfo(userInfo.getUserSeq());
		modelMap.put("userInfo", userInfo);
		modelMap.put("artclInfo", artclInfo);
		return VIEWSPACE + "/main";
	}

	private String getUserIdFromUri(String uri) {
		int atStart = VIEWSPACE.length() + 1;
		int atLast = uri.indexOf(".gom");
		if (atLast < 0) {
			atLast = uri.length();
		}
		String userId = uri.substring(atStart, atLast);
		log.info("## userId : " + userId);
		return userId;
	}
	
}
